<template>
  <div class="active-detail-view">
    <h2>活动详情</h2>
    <div v-if="activity.active">
      <el-card class="activity-card">
        <h3>{{ activity.active.name }}</h3>
        <p>{{ activity.active.description }}</p>
        <div class="activity-info">
          <el-row :gutter="20">
            <el-col :span="12">
              <span>活动类型: {{ activity.active.type }}</span>
            </el-col>
            <el-col :span="12">
              <span>活动范围: {{ activity.active.scope }}</span>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <span>开始时间: {{ activity.active.beginTime }}</span>
            </el-col>
            <el-col :span="12">
              <span>结束时间: {{ activity.active.endTime }}</span>
            </el-col>
          </el-row>

          <!-- 提交材料按钮 -->
          <el-row justify="end" class="upload-button">
            <el-button type="success" @click="openFileDialog">提交材料</el-button>
            <input type="file" ref="fileInput" style="display: none" accept="application/pdf" @change="handleFileChange" />
          </el-row>
        </div>
      </el-card>

      <el-card class="materials-card">
        <h4>提交材料</h4>
        <el-table :data="submitList.submitData" style="width: 100%">
          <el-table-column prop="name" label="材料名称" width="180" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewMaterial(row.materialId)">
                查看材料
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div v-else>
      <el-skeleton :rows="5" animated />
    </div>

    <!-- PDF Viewer Modal -->
    <el-dialog v-model="showModal" title="查看材料" width="80%">
      <iframe :src="pdfUrl" width="100%" height="600px"></iframe>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { getActivityDetail, getSubmitList, uploadMaterial } from '@/request/api';
import { InitData } from '@/type/active';
import { SubmitDetail } from '@/type/submitDetail';
import { ElMessageBox, ElMessage } from 'element-plus';

export default defineComponent({
  name: 'ActiveDetailView',
  setup() {
    const route = useRoute();
    const activity = reactive(new InitData());
    const submitList = reactive(new SubmitDetail());
    const showModal = ref(false);
    const pdfUrl = ref('');
    const id = route.params.id as string;//活动id

    const fileInput = ref<HTMLInputElement | null>(null);

    const fetchData = () => {
      getActivityDetail(Number(id))
          .then((res) => {
            activity.active = res.data.data;
          })
          .catch((error) => {
            console.error('Error fetching activity detail:', error);
          });

      getSubmitList(Number(id))
          .then((res) => {
            submitList.submitData = res.data.data;
            console.log("subdata",submitList.submitData);
            console.log("res",res);
          })
          .catch((error) => {
            console.error('Error fetching submit list:', error);
          });
    };

    const openFileDialog = () => {
      fileInput.value?.click();
    };

    const handleFileChange = async (event: Event) => {
      const file = (event.target as HTMLInputElement)?.files?.[0];
      if (!file) return;

      try {
        await ElMessageBox.confirm(
            '确定要上传这份材料吗？',
            '确认上传',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        );

        const userId = Number(id);
        const response = await uploadMaterial(Number(id), userId, file);

        if (response.data.code === 200) {
          ElMessage.success('材料上传成功！');
          fetchData(); // 重新获取材料列表
        } else {
          ElMessage.error('上传失败，请稍后再试。');
        }
      } catch {
        ElMessage.info('上传错误');
      }
    };

    const viewMaterial = (materialId: number) => {
      pdfUrl.value = `/path/to/material/${materialId}.pdf`; // 替换为实际的 PDF 路径
      showModal.value = true;
    };

    onMounted(() => {
      fetchData();
    });

    return {
      activity,
      submitList,
      showModal,
      pdfUrl,
      viewMaterial,
      fileInput,
      openFileDialog,
      handleFileChange,
    };
  },
});
</script>

<style scoped lang="scss">
.active-detail-view {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.activity-card,
.materials-card {
  margin-bottom: 20px;
  padding: 20px;
}

.upload-button {
  margin-top: 20px;
  text-align: right;
}

.el-dialog iframe {
  border: none;
}
</style>
